# coding: utf-8
# Author: zhenda
# Time  : 2021/12/13 14:50
from demo_student import *
import os
import time


class MySystem(object):
    def __init__(self):
        self.stu_dic = {}
        self.filename = '学生信息/student.txt'
        self.format_title = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}'
        self.format_data = '{:^6}\t{:^13}\t{:^8}\t{:^10}\t{:^10}\t{:^8}'

    # 菜单
    @staticmethod
    def _menu():
        print('===========================学生信息管理系统===============================')
        print('------------------------------功能菜单----------------------------------')
        print('\t\t\t1. 录入学生信息')
        print('\t\t\t2. 查找学生信息')
        print('\t\t\t3. 删除学生信息')
        print('\t\t\t4. 修改学生信息')
        print('\t\t\t5. 无')
        print('\t\t\t6. 统计学生总人数')
        print('\t\t\t7. 显示所有学生信息')
        print('\t\t\t0. 保存并退出系统')
        print('-----------------------------------------------------------------------')

    def _save(self):
        with open(self.filename, 'w', encoding='UTF_8') as wf:
            for item in self.stu_dic.values():
                wf.write(str(item) + '\n')

    def _load_data(self):
        try:
            with open(self.filename, 'r', encoding='utf-8') as rf:
                f_buf = rf.readlines()
                for item in f_buf:
                    item = eval(item)
                    s_tmp = Student(*item.values())  # 解包传参
                    s_no_tmp = item['id']
                    self.stu_dic[s_no_tmp] = s_tmp.__str__()
        except BaseException as e:
            print('出现异常：', e)

    def _backup(self):
        # 1. 判断存放数据的文件夹
        current_dir = os.getcwd()
        if not os.path.isdir(current_dir + '\\学生信息'):
            os.makedirs('学生信息')

        t = time.strftime('%Y-%m-%d_%H_%M_%S', time.localtime())
        t1 = os.path.splitext(self.filename)
        # print(t1[0] + time_str + t1[1])

        # 2. 重命名文件，复制文件
        try:
            with open(self.filename, 'r', encoding='UTF_8') as rfile:
                with open(t1[0] + t + t1[1], 'w', encoding='UTF_8') as wfile:
                    wfile.write(rfile.read())
        except BaseException as e:
            print('备份失败:', e)

    def start_sys(self):
        print('欢迎使用学生信息系统')
        self.__load_data()
        while True:  # 驿站 主界面
            self.__menu()
            try:
                rst = int(input('请选择功能编号'))
            except BaseException as e:
                print('发生错误:', e)
            else:
                if rst not in range(8):
                    print('输入错误，请重新输入')
                    continue
                else:
                    if rst == 0:
                        rst2 = input('您确定要退出吗？y/n')
                        if rst2 not in ['y', 'n']:
                            print('输入错误')
                            continue
                        if rst2 == 'y':
                            self.__backup()
                            self.__save()
                            print('谢谢使用')
                            break  # 退出
                        else:
                            continue  # 返回界面
                    elif rst == 1:
                        # self.__backup()
                        self.__insert()
                    elif rst == 2:
                        self.__search()
                    elif rst == 3:
                        # self.__backup()
                        self.__delete()
                    elif rst == 4:
                        # self.__backup()
                        self.__modify()
                    elif rst == 5:
                        self.__mysort()
                    elif rst == 6:
                        self.__total()
                    elif rst == 7:
                        self.__show_all()

    def _insert(self):
        while True:
            student_id = input('请输入id， 如1001:\n')
            if student_id in self.stu_dic.keys():
                print('已经存在此学号信息')
                continue
            name = input('请输入姓名:\n')
            try:
                english = int(input('请输入英语成绩:\n'))
                python = int(input('请输入python成绩:\n'))
                java = int(input('请输入java成绩:\n'))
            except BaseException as e:
                print('输入错误', e)
                continue
            # 学生信息放入字典中
            stu_tmp = Student(student_id, name, english, python, java)
            self.stu_dic[student_id] = stu_tmp.__str__()

            rst = input('是否输入下一位同学信息？y/n')
            if rst == 'y':
                continue
            else:
                break
        # self.__save2()
        print('学生信息保存完毕！')

    def _delete(self):
        self.__show_all()
        while True:
            student_id = input('请输入希望删除的学生id')
            if student_id not in self.stu_dic.keys():
                print('没有学生信息')
            else:
                print('找到学生信息')
                del self.stu_dic[student_id]
                print('删除成功')
                self.__show_all()

            rst = input('还要继续删除学生信息吗？y/n')
            if rst == 'y':
                continue
            else:
                break

    def _modify(self):
        stu_id = input('请输入希望修改的学生id')
        if stu_id not in self.stu_dic:
            print(f'学生id为{stu_id}的学生不存在')
        else:
            print('学生信息找到了，请修改：')
            try:
                name_tmp = input("请修改姓名:\n")
                english_tmp = int(input("请修改英语成绩:\n"))
                python_tmp = int(input("请修改python成绩:\n"))
                java_tmp = int(input("请修改java成绩:\n"))
            except BaseException as e:
                print('输入信息错误:', e, '请重新输入')
            else:
                s_tmp = Student(stu_id, name_tmp, english_tmp, python_tmp, java_tmp)
                self.stu_dic[stu_id] = s_tmp.__str__()
                print('修改信息完毕！')
        self.__show_all()
        answer = input('是否继续修改其他学生信息？y/n')
        if answer == 'y':
            self.__modify()
        else:
            return

    def _search(self):
        while True:
            stu_id = input('请输入希望查找的学生id')
            if stu_id not in self.stu_dic.keys():
                print('没有找到此学生信息')
            else:
                print('学生信息为:')
                print(self.stu_dic[stu_id])

            answer3 = input('是否继续查询学生信息？y/n')
            if answer3 == 'y':
                continue
            else:
                break

    def _total(self):
        print('一共%d个学生' % len(self.stu_dic))
        answer = input('是否继续？按空格继续')
        if answer == ' ':
            return

    def _show_all(self):
        for i in self.stu_dic.values():
            print(i)
        answer = input('是否继续？按空格继续')
        if answer == ' ':
            return

    def _mysort(self):
        pass


if __name__ == '__main__':
    time_str = ''
    t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    print(t)
    t1 = os.path.splitext('学生信息/student.txt')
    print(t1)

